package com.lsj.core.lock;

import cn.hutool.core.util.IdUtil;
import com.lsj.core.exception.CustomerException;
import com.lsj.core.response.ResponseType;
import com.lsj.core.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @Author:lin.sj
 * @Data:2021/7/12 19:47
 * @Desc: 分布式锁切面，实现方法级别的分布式锁
 */
@Component
@Slf4j
@Aspect
public class DistributedLockAop {
    @Autowired
    RedisUtil redisUtil;

    @Pointcut("@annotation(com.lsj.core.lock.DistributedLock)")
    public void pointCut(){}

    @Around(value = "pointCut()")
    public Object DistributedLockArround(ProceedingJoinPoint jp) throws Throwable {
        Object result = null;
        MethodSignature signature = (MethodSignature)jp.getSignature();
        DistributedLock lock = signature.getMethod().getDeclaredAnnotation(DistributedLock.class);
        String lockKey = lock.value().name();
        try {
            boolean lockSuccess = false;
            //获取锁，失败则自旋，默认尝试3次
            int maxRetry = lock.maxRetry();
            String uuid = IdUtil.fastSimpleUUID();
            while (!lockSuccess){
                lockSuccess = redisUtil.tryLock(lockKey,uuid);
                if(!lockSuccess){
                    //获取锁失败，500ms后重试
                    Thread.sleep(500);
                }
                maxRetry--;
                if(maxRetry < 1){
                    throw new CustomerException(ResponseType.system_error,"处理失败，请稍后尝试！");
                }
            }
            result = jp.proceed();
        } catch (Throwable throwable) {
            throw throwable;
        }finally {
            redisUtil.releaseLock(lockKey);
        }
        return result;
    }
}
